# -*- coding: utf-8 -*-
#!/usr/bin/python

# Clutter
import clutter
from clutter import keysyms

# Jumble
import jumble.classstylemanager

# Alicante
from widgets_manager import EventsManager
from events_manager import ClientHomeboxFactory
from utils.actions_mapping import KeyboardMapping
import utils.styles

# Utils
from twisted.internet import reactor
from threading import Thread
import gobject, logging, sys, getopt
from gobject.option import OptionParser, OptionGroup
import optparse

def Usage():
    print '\nUsage:'
    print 'interface.py [OPTION...]\n'
    print 'Options:'
    print '-h, --help              This usage text'
    print '-s, --serverip          Homebox ip'
    print '-p, --serverport        Homebox port'
    print '-i, --videoip           Video Server IP'
    print '-v, --videoport         Video Server port\n'
    

class mainApp():
    def __init__(self, config):
        self.videoport = config['videoport']
        self.videoServerIP = config['videoServerIP']
        self.serverIP = config['serverIP']
        self.serverPort = config['serverPort']

        # Init log
        log = logging.getLogger("AlicanteClutter")
        logging.basicConfig()
        log.setLevel(logging.DEBUG)
        log.info("Starting Clutter Interface")    
        
        # Init gobject (We need gobject to process clutter image operations)
        gobject.threads_init()
        self.mainloop = gobject.MainLoop()        

        # Init graphical environement
        clutter.threads_init()
        clutter.init()

    def quit(self, signal = None, frame = None):
        try:
            reactor.callFromThread(reactor.stop)
            self.events.stopEvent()
            self.mainloop.quit()
            self.twistedThread.join(3)
            self.twistedThread = None
        except:
            pass
        exit()
        
    def on_key_press(self, stage, event):
        if event.keyval == clutter.keysyms.Escape:
            self.quit()
           
    def run(self):
        stage = clutter.Stage(default=True)
        stage.set_color(clutter.Color(0, 0, 0, 255))
        stage.set_size(800, 600)
        stage.set_title("Alicante")
        stage.connect('destroy', clutter.main_quit)
        stage.connect('key-press-event', self.on_key_press)
        jumble.classstylemanager.registry.add_json_style(utils.styles.default_style)
        
        # Map actions: Keyboard, RemoteControl...
        mapping = KeyboardMapping()
        
        # Video/Channel Manager
        video = VideoChannel(stage, mapping, self.videoport, self.videoServerIP)
        video.initStreams()

        # Clutter Widget Manager
        self.events = EventsManager(stage, mapping)
        
        # Connect to the HomeBox
        reactor.connectTCP(self.serverIP, self.serverPort, ClientHomeboxFactory(self.events, video))    
        self.twistedThread = Thread( target = reactor.run, kwargs = {'installSignalHandlers':False} )
        self.twistedThread.setDaemon(True)
        self.twistedThread.start()
            
        #events.addExampleEvent("unzipwidgets/NMdYas5TpigO1XsC/event.py")
        ##twistedThread = Thread( target= events.addExampleEvent, kwargs = {'path':'unzipwidgets/5kXSRUyh5RhNbyVM/event.py'} )
        ##twistedThread.setDaemon(True)
        ##twistedThread.start()
        
        video.play()
        video.setChannel(1)
        stage.show_all()
        
        try:
            self.mainloop.run()
        except (KeyboardInterrupt, SystemExit):
            self.quit()

if __name__ == "__main__":    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hs:p:v:i:", ["help", "serverip=", "serverport=", "videoport=", "videoip="])
    except getopt.GetoptError:
        Usage()
        sys.exit(2)

    config = {"videoport":9000,
              "videoServerIP":"127.0.0.1", 
              "serverPort":7000,
              "serverIP":"127.0.0.1"}
    
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            Usage()
            sys.exit()
        elif opt in ("-s", "--serverip"):
            if arg == "demo":
                config['serverIP'] = '192.168.16.1'
            else:
                config['serverIP'] = arg
        elif opt in ("-p", "--serverport"):
            config['serverPort'] = arg
        elif opt in ("-v", "--videoport"):
            config['videoport'] = arg
        elif opt in ("-i", "--videoip"):
            if arg == "demo":
                config['videoServerIP'] = '192.168.16.1'
            else:
                config['videoServerIP'] = arg

    from video_manager import VideoChannel # Avoid gst usage message
    mainApp(config).run()
